#include "kontrast.h"

#include <QScreen>
#include <QImage>

#include <QCursor>
#include <QLabel>
#include <QKeyEvent>
#include <QMouseEvent>

#include <QClipboard>

#include <QSettings>

extern QLabel *lbl;

Kontrast::Kontrast(QObject *parent)
    : QObject{parent}
    , pscreen(QGuiApplication::primaryScreen())
    , psettings(new QSettings("Kontrast-clone", "FAVORITE_COLOR_LIST"))
    , _color("#000000")
    , _bkcolor("#ffffff")
    , _is_bk(false)
{
    // DEBUG
    // _color_pairs.append("#ffffff;#000000");
    // _color_pairs.append("#ffffff;#000000");
    // _color_pairs.append("#ffffff;#ff0000");
    // _color_pairs.append("#ffffff;#000000");
    // _color_pairs.append("#ffffff;#000000");

    // LOAD FAVORITE COLORS
    foreach (auto const &key, psettings->allKeys()) { _color_pairs.append(key); }
}

bool Kontrast::eventFilter(QObject *watched, QEvent *event) {
    if (event->type() == QEvent::KeyPress) {
        if (((QKeyEvent*)event)->key() == Qt::Key_Escape) {
            lbl->close();
        }
        event->ignore();
        return false;
    }
    if (event->type() == QEvent::MouseMove) {
        lbl->setCursor(Qt::CrossCursor);
    }
    if (event->type() == QEvent::MouseButtonPress) {
        auto mouse_event = (QMouseEvent*)event;
        if (_is_bk) {
            _bkcolor = pixmap.toImage().pixel(mouse_event->pos());
            emit bkcolorChanged();
            _is_bk = false;
        }
        else {
            _color = pixmap.toImage().pixel(mouse_event->pos());
            emit colorChanged();
        }
        lbl->setMouseTracking(false);
        lbl->setCursor(Qt::ArrowCursor);
        lbl->close();
    }
    return QObject::eventFilter(watched, event);
}

void Kontrast::pick(bool is_bk) {
    _is_bk = is_bk;
    if (pscreen) {
        pixmap = pscreen->grabWindow(0);
        lbl->setPixmap(pixmap);
        lbl->showFullScreen();
        lbl->setCursor(Qt::CrossCursor);
        lbl->setMouseTracking(true);
    }
    else
        qDebug() << "pscreen == nullptr!!!";
}

void Kontrast::mark_favorite() {
    auto const cpair = QString("%1;%2").arg(_color.name()).arg(_bkcolor.name());

    if (psettings->contains(cpair))
        return;

    psettings->setValue(cpair, true);  // ONLY USE KEY

    _color_pairs.append(cpair);
    emit color_pairsChanged();
}

void Kontrast::remove_favorite(int index) {
    if (!psettings->contains(_color_pairs[index])) {
        qDebug() << "impossible!!!";
    }
    psettings->remove(_color_pairs[index]);

    _color_pairs.removeAt(index);
    emit color_pairsChanged();
}

void Kontrast::copy(QString const color) {
    QGuiApplication::clipboard()->setText(color);
}
